package com.aljfce.business.profile.control;

import com.aljfce.business.entity.User;
import com.aljfce.business.mail.control.MailManager;
import java.security.Principal;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Jacopo, Antonio
 */
@Named
@Stateless
public class LoginManager {
    
    private User user;
    
    //TODO ANTONIO decidere se gli attributi con annotazioni sono dichiarati pubblici o privati
    @Resource
    SessionContext ctx;
    
    @Inject
    MailManager mailManager;
    
    @PersistenceContext
    EntityManager em;
    
    //TODO ANTONIO decidere se questi metodi useless vanno eliminati o meno
    //this is present in the design document but useless
    public void checkLogin(){
    }
    
    /**
     * This method checks the data entered by the user to login
     *
     * @param email A {@link String} representing user's email which is the user's primary key.
     * @param password A {@link String} representing the user's password.
     * @return {@link Boolean} true if the email exists in the database 
     * and the corresponding password is correct and false otherwise
     * 
     */
    public Boolean verifyLoginData(String email, String password) {
        
        if (email == null||password==null) {
            throw new IllegalArgumentException("User e/o password cannot be null");
        }
        
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        try {
            request.login(email, password);
        } catch (ServletException e) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Login failed.",null));
            return false;
        }
        
        //TODO ANTONIO fix this I think is useless
        Principal principal = request.getUserPrincipal();
        user=em.find(User.class, principal.getName());
        return true;
    }
    
    //this is present in the design document but useless
    public void loadUser(){
    }
    
    /**
     * This method will invalidate the current session context
     */
    public void logout(){
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        request.getSession().invalidate();
    }

}
